<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="所属项目" prop="projectId">
        <el-select
            class="search-width-middle"
            filterable clearable v-model="queryParams.projectId" placeholder="请选择所属项目">
          <el-option
              v-for="item in allProjectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="甲方名称" prop="principalName">
        <el-input maxlength="50"
                  class="search-width-middle"
                  v-model="queryParams.principalName"
                  placeholder="请输入委托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="受托方名称" prop="trusteeName">
        <el-input maxlength="50"
                  class="search-width-middle"
                  v-model="queryParams.trusteeName"
                  placeholder="请输入受托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="classifyCode">
        <el-select filterable clearable
                   class="search-width-middle"
                   v-model="queryParams.classifyCode" placeholder="请选择项目类型">
          <el-option
              v-for="dict in project_classify"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款状态" prop="status">
        <el-select class="search-width-middle" clearable v-model="queryParams.status" placeholder="请选择状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款时间" prop="receiptTime">
        <el-date-picker class="search-width-middle"
                        v-model="queryParams.receiptTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        @change="handleTime">
        </el-date-picker>
      </el-form-item>
      <el-form-item style="margin-left: 20px">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['biz:bizReceipt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:bizReceipt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:bizReceipt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['biz:bizReceipt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizReceiptList" border>
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.receiptList"
                    row-class-name="success-row"
                    border
                    style="width:calc(100vw - 90px)"
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="left" />
            <el-table-column label="序号" type="index" align="left" width="60" />
            <el-table-column label="收款金额" align="left" prop="receiptMoney" width="180" >
              <template #default="scope">
                <span>{{formatMoney(scope.row.receiptMoney)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="收款时间" align="left" prop="receiptTime" width="180"/>
            <el-table-column label="状态" align="left" prop="status" width="120">
              <template #default="scope">
                <span>{{scope.row.status==0?'待收款':'已收款'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="款项名称" align="left" prop="receiptName" />
            <el-table-column label="备注" align="left" prop="memo" show-overflow-tooltip/>
            <el-table-column label="创建人" align="left" prop="userName" width="120"/>
            <el-table-column label="创建时间" align="left" prop="createTime" width="180"/>
            <el-table-column label="操作" align="left" width="90" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                             v-hasPermi="['biz:bizInvoice:edit']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                             v-hasPermi="['biz:bizInvoice:remove']">
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" align="left" width="60" />
      <el-table-column label="项目名称" align="left" prop="projectName" min-width="200" show-overflow-tooltip/>
      <el-table-column label="项目板块" align="left" prop="sectorName" width="160" show-overflow-tooltip/>
      <el-table-column label="合同金额" align="left" prop="totalAmount" width="180">
        <template #default="scope">
          <span>{{formatMoney(scope.row.totalAmount)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="已收款金额" align="left" prop="receivedAmount" width="180">
        <template #default="scope">
          <span>{{formatMoney(scope.row.receivedAmount)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="未收款金额" align="left" prop="unReceivedAmount" width="180">
        <template #default="scope">
          <span>{{formatMoney(scope.row.unReceivedAmount)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划收款次数" align="left" prop="receiptPlan" width="180">
        <template #default="scope">
          <el-popover placement="bottom" :width="430" trigger="hover">
            <template #reference>
              <el-text style="color: blue;cursor: pointer;">{{scope.row.receiptPlan}}</el-text>
            </template>
            <el-table :data="scope.row.planList">
              <el-table-column prop="stage" label="阶段" width="140"/>
              <el-table-column prop="time" label="时间" width="130"/>
              <el-table-column prop="money" label="款项金额" width="130"/>
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="实际收款次数" align="left" prop="receiptReal" width="180"/>
      <el-table-column fixed="right" label="操作" align="left" width="110">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleNew(scope.row)"
                     v-hasPermi="['biz:bizInvoice:edit']">收款登记</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收款登记对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="800px" append-to-body @close="cancel">
      <el-form ref="bizReceiptRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="剩余收款额" class="custom-red-label-color">
          <el-text style="color:red">{{surplusAmount}}</el-text>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select :disabled="!selectProject" filterable clearable v-model="form.projectId" @change="changeProject" placeholder="请选择所属项目">
            <el-option
                v-for="item in allProjectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款金额" prop="receiptMoney">
          <CurrencyInput maxlength="50" v-model="form.receiptMoney" placeholder="请输入收款金额" />
        </el-form-item>
        <el-form-item label="收款时间" prop="receiptTime">
          <el-date-picker clearable
            v-model="form.receiptTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="请选择收款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="款项名称" prop="receiptName">
          <el-input maxlength="50" v-model="form.receiptName" placeholder="请输入款项名称" />
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input maxlength="500" v-model="form.memo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-select v-model="form.status" placeholder="请选择状态">-->
<!--            <el-option-->
<!--                v-for="item in options"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BizReceipt">
import { getSurplus,listBizReceipt, getBizReceipt, delBizReceipt, addBizReceipt, updateBizReceipt } from "@/api/biz/bizReceipt";
import {listAllProject} from "@/api/biz/bizProject";
import CurrencyInput from '@/components/CurrencyInput.vue';
import {currentDate} from '@/utils/dateutil';
import {formatMoney} from '@/utils/money';

const { proxy } = getCurrentInstance();
const { project_classify } = proxy.useDict('project_classify');
const route = useRoute();
const router = useRouter();
const paramProjectId = ref('');
paramProjectId.value = route.query.receiptProjectId;
// 计算属性用于获取查询参数 t
const queryParamT = computed(() => route.query.receiptProjectId);
// 监听 queryParamT 的变化
watch(queryParamT, (newValue, oldValue) => {
  paramProjectId.value = newValue;
  receiptListAllProject();
});
const options = [
  {
    value: 0,
    label: '待收款',
  },
  {
    value: 1,
    label: '已收款',
  }
]
const allProjectList = ref([]);
const bizReceiptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectProject = ref(true);
const surplusAmount = ref(0);
const add=ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    principalName: null,
    trusteeName: null,
    classifyCode: null,
    status: null,
    receiptTimeStart: null,
    receiptTimeEnd: null,
  },
  rules: {
    projectId: [
      { required: true, message: "所属项目不能为空", trigger: "submit" }
    ],
    receiptMoney: [
      { required: true, message: "收款金额不能为空", trigger: "submit" }
    ],
    receiptTime: [
      { required: true, message: "收款时间不能为空", trigger: "submit" }
    ],
    status: [
      { required: true, message: "请选择状态", trigger: "submit" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询收款登记列表 */
function getList() {
  loading.value = true;
  listBizReceipt(queryParams.value).then(response => {
    bizReceiptList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  const {receiptProjectId, ...query} = route.query;
  router.replace({path: route.path, query});
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    projectId: null,
    receiptReason: null,
    receiptType: null,
    cardNumber: null,
    receiptMoney: null,
    receiptUserId: null,
    receiptTime: null,
    status: 1,
    memo: null,
    userId: null
  };
  proxy.resetForm("bizReceiptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleTime(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  selectProject.value=true;
  open.value = true;
  title.value = "添加收款登记";
  add.value=0;
}

function handleNew(row) {
  reset();
  selectProject.value=false;
  open.value = true;
  title.value = "添加收款登记";
  form.value.projectId = row.projectId;
  add.value=0;
  changeProject();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBizReceipt(_id).then(response => {
    form.value = response.data;
    add.value=form.value.receiptMoney;
    selectProject.value=true;
    open.value = true;
    title.value = "修改收款登记";
    changeProject();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizReceiptRef"].validate(valid => {
    if (valid) {
      if(form.value.receiptMoney > surplusAmount.value){
        proxy.$modal.msgError("收款金额不能大于剩余收款额");
        return;
      }
      if (form.value.id != null) {
        updateBizReceipt(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBizReceipt(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除收款登记数据项？').then(function() {
    return delBizReceipt(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/bizReceipt/export', {
    ...queryParams.value
  }, `收款登记-${currentDate()}.xlsx`)
}

function receiptListAllProject() {
  listAllProject({}).then(response => {
    allProjectList.value = response.data;
    if (paramProjectId.value) {
      //参数存在，打开弹窗
      reset();
      open.value = true;
      title.value = "添加收款登记";
      form.value.projectId = Number(paramProjectId.value);
    }
  });
}

function handleTime(value) {
  queryParams.value.receiptTimeStart=null;
  queryParams.value.receiptTimeEnd=null;
  if (value && value.length > 0) {
    queryParams.value.receiptTimeStart = value[0]+" 00:00:00";
  }
  if (value && value.length > 1) {
    queryParams.value.receiptTimeEnd = value[1]+" 23:59:59";
  }
}

function changeProject() {
  getSurplus(form.value.projectId).then(response => {
    surplusAmount.value = response.data+add.value;
  });
}
getList();
receiptListAllProject();
</script>
<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
